package class_sources;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Properties;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import android.util.Log;

public class XMLProc {
	public Boolean DeleteXML(String path)
	{
		File file = new File(path);
		return  file.delete();
	}
	public void AppendXML(String path,HashMap<String, String> tagsNvalues) throws Exception
	{
		DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        Document doc = docBuilder.parse (new File(path));
        Node node = doc.getElementsByTagName("RoadShip").item(0);
        Iterator<String> myVeryOwnIterator = tagsNvalues.keySet().iterator();
        while(myVeryOwnIterator.hasNext()) {
            String key=(String)myVeryOwnIterator.next();
            String value=(String)tagsNvalues.get(key);
            Element newelmnt = doc.createElement(key);
            newelmnt.appendChild(doc.createTextNode(value));
            node.appendChild(newelmnt);
        }
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File(path));
        transformer.transform(source, result);
	}
	
	public void ModifyNode(String path,String nodeName,String newValue) throws Exception
	{
		DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
	    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
	    Document doc = docBuilder.parse(new File(path));
	    Node nodes = doc.getElementsByTagName(nodeName).item(0);
	    if(nodes!=null)
	    {
	    	nodes.setTextContent(newValue);
		    Transformer transformer = TransformerFactory.newInstance().newTransformer();
		    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
		    StreamResult result = new StreamResult(path);
		    DOMSource source = new DOMSource(doc);
		    transformer.transform(source, result);
	    }
	    else
	    	Log.i("ERROR", "HATA Muhtemelen nodes==null");
	}
	
	public void CreateXML(String path,HashMap<String, String> tagsNvalues)
	{
		try {
	        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
	                      .newInstance();
	            DocumentBuilder documentBuilder = documentBuilderFactory
	                      .newDocumentBuilder();
	            Document document = documentBuilder.newDocument();

	            Element rootElement = document.createElement("RoadShip");
	            document.appendChild(rootElement);
	            Iterator<String> myVeryOwnIterator = tagsNvalues.keySet().iterator();
	            while(myVeryOwnIterator.hasNext()) {
	                String key=(String)myVeryOwnIterator.next();
	                String value=(String)tagsNvalues.get(key);
	                Element editionElement = document.createElement(key);
		            rootElement.appendChild(editionElement);
		            editionElement.appendChild(document.createTextNode(value));
	            }
	            TransformerFactory factory = TransformerFactory.newInstance();
	            Transformer transformer = factory.newTransformer();
	            Properties outFormat = new Properties();
	            outFormat.setProperty(OutputKeys.INDENT, "yes");
	            outFormat.setProperty(OutputKeys.METHOD, "xml");
	            outFormat.setProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
	            outFormat.setProperty(OutputKeys.VERSION, "1.0");
	            outFormat.setProperty(OutputKeys.ENCODING, "UTF-8");
	            transformer.setOutputProperties(outFormat);
	            DOMSource domSource = 
	            new DOMSource(document.getDocumentElement());
	            OutputStream output = new ByteArrayOutputStream();
	            StreamResult result = new StreamResult(output);
	            transformer.transform(domSource, result);
	            String xmlString = output.toString();
	            FileOutputStream fOut = new FileOutputStream(new File(path));
	            OutputStreamWriter osw = new OutputStreamWriter(fOut);  
	            String fileContent =xmlString; //build file content
	            osw.write(fileContent); 
	            osw.flush(); 
	            osw.close();
	        } catch (Exception e) {
	        	e.printStackTrace();
	        }
	}
	
	public HashMap<String, String> ReadXML(String path) throws Exception
	{
		HashMap<String, String> mp=new HashMap<String, String>();
		String xml=readFileAsString(path);
		Document doc=getDomElement(xml);
		NodeList n=doc.getElementsByTagName("RoadShip");
		for(int i=0;i<n.getLength();i++)
		{
			Element e=(Element)n.item(i);
			mp.put("username", getValue(e, "username"));
			mp.put("password", getValue(e, "password"));
			mp.put("session", getValue(e, "session"));
			mp.put("showUserProps", getValue(e, "showUserProps"));
			mp.put("locationX", getValue(e, "locationX"));
			mp.put("locationY", getValue(e, "locationY"));
			mp.put("isDriver", getValue(e, "isDriver"));
		}
		return mp;
	}
	private static String readFileAsString(String filePath)
		    throws java.io.IOException{
		        StringBuffer fileData = new StringBuffer(1000);
		        BufferedReader reader = new BufferedReader(
		                new FileReader(filePath));
		        char[] buf = new char[1024];
		        int numRead=0;
		        while((numRead=reader.read(buf)) != -1){
		            String readData = String.valueOf(buf, 0, numRead);
		            fileData.append(readData);
		            buf = new char[1024];
		        }
		        reader.close();
		        return fileData.toString();
		    }
	public String getValue(Element item, String str) {
	    NodeList n = item.getElementsByTagName(str);
	    return getElementValue(n.item(0));
	}
	
	public final String getElementValue( Node elem ) {
        Node child;
        if( elem != null){
            if (elem.hasChildNodes()){
                for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
                    if( child.getNodeType() == Node.TEXT_NODE  ){
                        return child.getNodeValue();
                    }
                }
            }
        }
        return "";
	} 
	public Document getDomElement(String xml){
		Document doc = null;
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		try {
			DocumentBuilder db = dbf.newDocumentBuilder();
			InputSource is = new InputSource();
		        is.setCharacterStream(new StringReader(xml));
		        doc = db.parse(is); 

			} catch (Exception e) {
				Log.e("Error: ", e.getMessage());
				return null;
			}
                // return DOM
	        return doc;
	}
	
	public boolean IsRegisteredUser(String path)
	{
		File f=new File(path);
		return f.exists();
	}
}
